package org.corey.share.misc;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import org.corey.share.db.entity.CoreyFile;

import com.google.appengine.api.datastore.Blob;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

@SuppressWarnings("unchecked")
public class FileUploadInvocation extends AbstractInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private int maxSize;
	private String allowNames;

	public int getMaxSize() {
		return maxSize;
	}

	public void setMaxSize(int maxSize) {
		this.maxSize = maxSize;
	}

	public String getAllowNames() {
		return allowNames;
	}

	public void setAllowNames(String allowNames) {
		this.allowNames = allowNames;
	}

	
	@Override
	public String intercept(ActionInvocation ai) throws Exception {
		Object action = ai.getAction();
		UploadAction uploadAction = null;
		if (!(action instanceof UploadAction)) {
			throw new IllegalStateException();
		} else {
			uploadAction = (UploadAction) action;
		}
		ActionContext ac = ai.getInvocationContext();
		HttpServletRequest request = (HttpServletRequest) ac
				.get(ServletActionContext.HTTP_REQUEST);
		ServletFileUpload fileUpload = new ServletFileUpload();
		if(this.getMaxSize()!=0){
			fileUpload.setSizeMax(this.getMaxSize());
		}else{
			fileUpload.setSizeMax(102400L);
		}
		
		
			    
		List<CoreyFile> coreyFiles=new ArrayList<CoreyFile>();
		
		if (ServletFileUpload.isMultipartContent(request)) {
			FileItemIterator iter;
				iter = fileUpload.getItemIterator(request);
				while (iter.hasNext()) {
				    FileItemStream item = iter.next();
				if (item.isFormField()) {
					;
				} else {
					CoreyFile file = new CoreyFile();
					String contentType = item.getContentType();
					String fileName = item.getName();
					Blob content = new Blob(IOUtils.toByteArray(item
							.openStream()));
					file.setContentType(contentType);
					file.setContent(content);
					file.setFileName(fileName);
					coreyFiles.add(file);
				}
			}
			uploadAction.setFiles(coreyFiles);
		} else {
			;
		}
		return ai.invoke();
	}

}
